<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <!-- 使用needs_validation需要依赖jquery和bootstrap.js -->
    <script src="../js/jquery-3.7.1.min.js"></script>
    <script src="../js/bootstrap.bundle.js"></script>
    <title>表单校验</title>
</head>
<body>
    <div class="container">
        <!-- .needs-validation开启boostrap的表单校验，用户点提交时才开始校验 -->
        <!-- novalidate关闭H5默认的表单校验 -->
        <form class="needs-validation" novalidate >
            <div class="form-group">
                <label >用户名</label>
                <input type="text" class="form-control" placeholder="用户名" required>
                <!-- 校验的提示文字用div装， -->
                <!-- .valid-feedback是校验通过 -->
                <!-- .invalid-feedback是校验失败 -->
                <div class="valid-feedback">通过</div>
                <div class="invalid-feedback">请填写用户名</div>
            </div>
            <div class="form-group">
                <label >密码</label>
                <input type="password" class="form-control" placeholder="密码" required>
                <div class="valid-feedback">通过</div>
                <div class="invalid-feedback">请填写密码</div>
            </div>
            <div class="form-group form-check">
                <label class="form-check-lable">
                  <input type="checkbox" class="form-check-input" required>我同意条款
                  <div class="valid-feedback">通过</div>
                <div class="invalid-feedback">必须同意条款才能进行登录</div>
                </label>
            </div>
            <button type="submit" class="btn btn-primary">登录</button>
        </form>
    </div>
</body>
<script>
    //通过类名获取到页面内所有的需要校验的表单
    // 监听这些表单的提交事件，如果表单要提交，就添加.was-validated到表单进行校验
(function() {
  'use strict';
  window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>
</html>